package com.ian.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Witt
 * @version 1.0.0
 * @date 2022/5/5
 */
@Controller
public class IndexController {

    @GetMapping("/")
    public String index(Model model, @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                        @AuthenticationPrincipal OAuth2User oauth2User) {
        System.out.println("@GetMapping(\"/\")");
        model.addAttribute("userName", oauth2User.getName());
        model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
        model.addAttribute("userAttributes", oauth2User.getAttributes());
        return "index";
    }

    @GetMapping("/test")
    @ResponseBody
    public String test() {
        return "test after authenticated";
    }

    @Autowired
    private RestTemplate restTemplate;

    /*@GetMapping("/index2.html")
    public String index() {
        return "index";
    }*/

    /*
    自定义回调地址的配套处理方法
    @GetMapping("/authorization_code")
//    @ResponseBody
    // 如果传入的实参名称和形参名称相同，@RequestParam注解可省略
    public String authorization_code(@RequestParam String code, String state) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "de91bdadc6b6b3599bebfa8755850fca0844aae44f13cc5e076110e961d4b59e");
        map.put("client_secret", "6baa392358c93949b4f5e9e443dfa646746eb40c67ffa3eb87decb408d500b77");
//        map.put("state", "witt");
        map.put("state", state);
        map.put("code", code);
        *//*
         redirect_uri：如果是自定义的 redirect_uri，这个参数是必须的，并且必须配置为 和 gitee中配置的应用回调地址 相同；
                       如果使用默认的 redirect_uri，不需要这个参数。
         *//*
        map.put("redirect_uri", "http://localhost:8060/authorization_code");
        map.put("grant_type", "authorization_code"); // 这个参数是必须的，否则报错：org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]。其也可以拼接在 url 的后面，像下面这样：
//        Map<String, String> resp = restTemplate.postForObject("https://gitee.com/oauth/token?grant_type=authorization_code", map, Map.class);
        Map<String, String> resp = restTemplate.postForObject("https://gitee.com/oauth/token", map, Map.class);
        System.out.println(resp);
        HttpHeaders httpheaders = new HttpHeaders();
        httpheaders.add("Authorization", "token " + resp.get("access_token"));
        HttpEntity<?> httpEntity = new HttpEntity<>(httpheaders);
        ResponseEntity<Map> exchange = restTemplate.exchange("https://gitee.com/api/v5/user", HttpMethod.GET, httpEntity, Map.class);
        String responseBodyStr = new ObjectMapper().writeValueAsString(exchange.getBody());
        System.out.println("exchange.getBody() = " + responseBodyStr);

        *//*
        必须处理返回内容，否则thymeleaf会自动处理模板 authorization_code，也就是请求的 uri，但是没有这个模板，所以报错；
        2022-05-16 16:35:36.148 ERROR 27512 --- [nio-8060-exec-3] org.thymeleaf.TemplateEngine: [THYMELEAF][http-nio-8060-exec-3] Exception processing template "authorization_code": Error resolving template [authorization_code], template might not exist or might not be accessible by any of the configured Template Resolvers
        org.thymeleaf.exceptions.TemplateInputException: Error resolving template [authorization_code], template might not exist or might not be accessible by any of the configured Template Resolvers

        要使其不报错，可以在方法上加注解 @ResponseBody，但是页面的处理到此为止，不会跳转到首页了。
        方法1：尝试返回内容，此处直接返回获取到的用户信息的json字符串，直接把字符串内容返回到页面上了，不大好看。代码如下：
                    return responseBodyStr;
        方法2：重定向到 首页，即 http://localhost:8060/。代码如下：
                    return "redirect:/";
              但是会报错：HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]

        最终发现，自定义回调地址，还是有问题，本地还是无法认证成功，只是能从gitee获取一些用户信息而已。
                    还是默认的回调地址吧！
         *//*
        return "redirect:/"; // 重定向到 首页，又报其他错误，算了
//        return responseBodyStr; // 直接把字符串内容返回到页面上了，不大好看
    }*/
}
